package com.zzti.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zzti.pojo.Goods;
import com.zzti.pojo.SysResult;
import com.zzti.pojo.Visiter;
import com.zzti.serviceImpl.GoodsServiceImpl;
import com.zzti.serviceImpl.OrderGoodsServiceImpl;
import com.zzti.serviceImpl.VisiterServiceImpl;
import com.zzti.util.CosApi;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class VisiterController {
    @Autowired
    private VisiterServiceImpl visiterServiceImpl;

    @Autowired
    private GoodsServiceImpl goodsServiceImpl;

    @Autowired
    private OrderGoodsServiceImpl orderGoodsServiceImpl;

    @Autowired
    private CosApi cosApi;

    //访客查看自身或他人信息,根据参数id来查找个人信息,返回一个Visiter对象
    @RequestMapping("/visiter/findOne")
    @ResponseBody
    public Visiter findOne(Integer id) {
        return visiterServiceImpl.findOne(id);
    }

    @RequestMapping("/visiter/delete")
    @ResponseBody
    //管理员或服务员删除访客信息，参数id数组，返回对象SysResult.status=200则表示成功
    public SysResult deleteById(Integer[] ids) {
        if (visiterServiceImpl.deleteByIds(ids) > 0) {
            return SysResult.success();
        } else {
            return SysResult.fail();
        }
    }

    @RequestMapping("/visiter/add")
    @ResponseBody
    //用户注册时调用,参数Visiter对象，返回值大于0则成功
    public SysResult add(Visiter vs) {
        if (visiterServiceImpl.add(vs) > 0) {
            return SysResult.success();
        } else {
            return SysResult.fail();
        }
    }


    @RequestMapping("/visiter/addV")
    @ResponseBody
    //用户注册时调用,参数Visiter对象，返回值大于0则成功
    public SysResult add(String name, String account, String password, Integer sex) {
        Visiter vs1 = new Visiter(null, name, account, password, null, null,
                -1, sex, 0, 0.00, null, null, null, null);
        System.out.println(vs1);
        if (visiterServiceImpl.add(vs1) > 0) {
            return SysResult.success();
        } else {
            return SysResult.fail();
        }
    }

    @RequestMapping("/index1")
    public String index() {
        return "redirect:website.html";
    }

    @RequestMapping("visiter/login")
    public String login(String account, String password, HttpSession session, HttpServletResponse response, HttpServletRequest request, Model model) {
        Visiter vis = visiterServiceImpl.login(account, password);
        if (vis != null) {
            session.setAttribute("user", vis);
            Cookie cookie = new Cookie("account", vis.getAccount());
            model.addAttribute("user", vis);
            cookie.setMaxAge(30 * 24 * 60 * 60);
            cookie.setPath(request.getContextPath());
            response.addCookie(cookie);
            return "user.html";
        } else return "redirect:/login.html";
    }

    @RequestMapping("/visiter/test333/{id}")
    public String wdas(@PathVariable("id") Integer id, Model model) {
        Visiter vis = visiterServiceImpl.findOne(id);
        model.addAttribute("user", vis);
        System.out.println(vis.toString());
        return "222.html";
    }

    @RequestMapping("/visiter/update")
    @ResponseBody
    public String dwad(String data) {
        System.out.println(data);
        Visiter vis = new Visiter();
        JSONObject js = JSON.parseObject(data);
        vis.setAccount(js.getString("account"));
        vis.setName(js.getString("userName"));
        vis.setSex(js.getIntValue("sex"));
        vis.setAge(js.getIntValue("age"));
        vis.setComment(js.getString("comment"));
        if (visiterServiceImpl.update(vis) > 0) {
            return JSON.toJSONString(SysResult.success());
        } else {
            return JSON.toJSONString(SysResult.fail());
        }
    }

    //用户修改信息时调用,参数Visiter对象，返回值大于0则成功
    @RequestMapping("/visiter/updateH/")
    @ResponseBody
    public SysResult update(Visiter vs) {
        Visiter vs1 = new Visiter(vs.getId(), vs.getName(), vs.getAccount(), vs.getPassword()
                , null, null, vs.getAge(), vs.getSex(), 1, vs.getMoney()
                , new Date(), new Date(), vs.getStatus(), vs.getTeamMessage());
        if (visiterServiceImpl.updateById(vs1) > 0)
            return SysResult.success();
        else
            return SysResult.fail();
    }


    @ResponseBody
    @RequestMapping("/visiter/upload/{id}")
    public SysResult upload(MultipartFile file, HttpServletRequest request, @PathVariable Integer id) {
        System.out.println(id);
        SysResult sysResult = cosApi.uploadObject(file);
        System.out.println(sysResult.getData());
        //保存上传
        if (file != null) {
            String filepath = (String) sysResult.getData();
            //打印查看上传路径
            Visiter vs = new Visiter();
            vs.setPhoto(filepath.toString());
            vs.setId(id);
            System.out.println(vs.toString());
            visiterServiceImpl.update(vs);
            return SysResult.success(filepath);
        }
        return null;

    }

    @RequestMapping("/visiter/toGoods/{id}")
    public String wdhas(@PathVariable("id") Integer id, Model model) {
        Visiter vis = visiterServiceImpl.findOne(id);
        model.addAttribute("user", vis);
        return "goods.html";
    }

    @ResponseBody
    @RequestMapping("/visiter/purchase")
    public String wdhas(Double price, Integer userId, Integer goodsId, Integer number, String address) {
        Visiter vis = visiterServiceImpl.findOne(userId);
        Goods g = goodsServiceImpl.findOneGoods(goodsId);
        Double now = vis.getMoney();
        if (g.getNumber() < number) {
            return JSON.toJSONString(SysResult.fail(new String("抱歉，该商品目前仅余" + g.getNumber() + "件")));
        }
        if (price * number > now) {
            return JSON.toJSONString(SysResult.fail("余额不足,请充值"));
        }
        if (price * number <= now) {
            vis.setMoney(now - price * number);
            visiterServiceImpl.update(vis);
            orderGoodsServiceImpl.add(userId, goodsId, number, price, address);
            g.setNumber(g.getNumber() - number);
            goodsServiceImpl.update(g);
            return JSON.toJSONString(SysResult.success("购买成功"));
        }
        return "";
    }

    @RequestMapping("/visiter/toServer/{id}")
    public String wdhasq(@PathVariable("id") Integer id, Model model) {
        Visiter vis = visiterServiceImpl.findOne(id);
        model.addAttribute("user", vis);
        return "server.html";
    }

    @RequestMapping("/visiter/toTeam/{id}")
    public String wdhasqw(@PathVariable("id") Integer id, Model model) {
        Visiter vis = visiterServiceImpl.findOne(id);
        model.addAttribute("user", vis);
        return "team.html";
    }

    @RequestMapping("/visiter/toEquipment/{id}")
    public String wdhasqwq(@PathVariable("id") Integer id, Model model) {
        Visiter vis = visiterServiceImpl.findOne(id);
        model.addAttribute("user", vis);
        return "equipment.html";
    }

    @RequestMapping("/visitor/findOther")
    @ResponseBody
    public String findOther(@RequestParam("limit") Integer limit, @RequestParam("page") Integer page, HttpServletRequest request,
                            @RequestParam(name = "userName", required = false, defaultValue = "") String userName) {
        Map<String, Object> ret = new HashMap<>();
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("userName", userName);
        List<Visiter> aaa = visiterServiceImpl.findOther(queryMap);
        queryMap.put("page", (page - 1) * limit);
        queryMap.put("limit", limit);
        JSONArray ja = new JSONArray();
        List<Visiter> ls = visiterServiceImpl.findOther(queryMap);
        return JSON.toJSONString(SysResult.success(ls, VisiterServiceImpl.count));
    }

    @ResponseBody
    @RequestMapping("/visitor/addTeam")
    public String wdhass(Integer userId, String teamMessage, Model model) {
        System.out.println(teamMessage);
        Visiter vis = visiterServiceImpl.findOne(userId);
        if (vis.getStatus() == 1) {
            return JSON.toJSONString(SysResult.success("您已经在组队中了"));
        } else {
            vis.setStatus(1);
            vis.setTeamMessage(teamMessage);
            visiterServiceImpl.update(vis);
            return JSON.toJSONString(SysResult.success("成功加入"));
        }
    }

    @ResponseBody
    @RequestMapping("/visitor/updateStatus")
    public String wdhass(Integer userId) {
        Visiter vis = visiterServiceImpl.findOne(userId);
        if (vis.getStatus() == 1) {
            vis.setStatus(0);
            visiterServiceImpl.update(vis);
            return JSON.toJSONString(SysResult.success("成功退出"));
        } else {
            return JSON.toJSONString(SysResult.success("您还未发布组队信息"));
        }
    }

    @ResponseBody
    @GetMapping("visiter/register")
    public SysResult register(String userName, String email, String password) {
        System.out.println(userName);
        System.out.println(email);
        System.out.println(password);
        Visiter vis = new Visiter();
        vis.setAccount(email);
        vis.setPassword(password);
        vis.setName(userName);
        vis.setCreateTime(new Date());
        visiterServiceImpl.add(vis);
        return SysResult.success();
    }


    //访客查看自身或他人信息,根据参数id来查找个人信息,返回一个Visiter对象
    @RequestMapping("/visiter/findOne/{id}")
    public String findOne(@PathVariable("id") Integer id, Model model) {
        Visiter one = visiterServiceImpl.findOne(id);
        model.addAttribute("visiter", one);
        return "view/user/user-form.html";
    }

    //管理员或服务员查看所有的访客信息，无参数，返回一个包含所有Visiter对象的列表
    @RequestMapping("/visiter/findAll")
    @ResponseBody
    public String findAll(Integer page, int limit, HttpServletRequest request,
                          @RequestParam(name = "visiterName", required = false, defaultValue = "") String visiterName
            , @RequestParam(name = "account", required = false, defaultValue = "") String account
            , @RequestParam(name = "status", required = false, defaultValue = "") String status) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("visiterName", visiterName);
        queryMap.put("account", account);
        queryMap.put("status", status);
        List<Visiter> aaa = visiterServiceImpl.findAll(queryMap);
        queryMap.put("page", (page - 1) * limit);
        queryMap.put("limit", limit);
        List<Visiter> all = visiterServiceImpl.findAll(queryMap);
        System.out.println(all.toString());
        String s = JSON.toJSONString(all);
        System.out.println(s);
        return "{\"count\":" + aaa.size() + ", \"code\":0 , \"data\":" + s + "}";

    }

    @RequestMapping("/visiter/delete/{id}")
    @ResponseBody
    //管理员或服务员删除访客信息，参数id数组，返回对象SysResult.status=200则表示成功
    public SysResult deleteById2(@PathVariable("id") Integer[] ids) {
        if (visiterServiceImpl.deleteByIds(ids) > 0)
            return SysResult.success();
        else
            return SysResult.fail();
    }

}
